// components/qrcode/qrcode.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isqrcode:{
      type:Boolean,
      value:false
    },
    qrcode:{
      type:String,
      value:''
    }

  },

  /**
   * 组件的初始数据
   */
  data: {
    
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onsaveqrcode(e){
      let that = this;
      wx.getSetting({ //获取用户的当前设置
        success: (res) => {
          console.log(res);
          if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
            that.saveImageToPhotosAlbum();
          } else {
            wx.authorize({ //如果没有授权，向用户发起请求
              scope: 'scope.writePhotosAlbum',
              success: () => {
                that.saveImageToPhotosAlbum();
              },
              fail: () => {
                wx.openSetting({
                  success(settingdata) {
                    console.log("settingdata", settingdata)
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      wx.showModal({
                        title: '提示',
                        content: '获取权限成功,再次点击图片即可保存',
                        showCancel: false,
                      })
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: '获取权限失败，将无法保存到相册哦~',
                        showCancel: false,
                      })
                    }
                  },
                })
              }
            })
          }
        }
      })

  },


  saveImageToPhotosAlbum() {
    let that = this;
    let qrcode = that.data.qrcode;
    let base64 = qrcode.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
    let filePath = wx.env.USER_DATA_PATH + '/hym_pay_qrcode.png';
    wx.getFileSystemManager().writeFile({
      filePath: filePath, //创建一个临时文件名
      data: base64, //写入的文本或二进制数据
      encoding: 'base64', //写入当前文件的字符编码
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: filePath,
          success: function(res2) {
            that.setData({
              isqrcode:false
            })
            wx.showToast({
              title: '保存成功，请从相册选择再分享',
              icon: "none",
              duration: 5000
            })
          },
          fail: function(err) {
            // console.log(err.errMsg);
          }
        })
      },
      fail: err => {
        //console.log(err)
      }
    })
  },

// 关闭    
    onshutdown(e){
      let that = this;
      that.setData({
        isqrcode:false
      })
    },
  }
})
